package com.wushi.lenovo.asia5b.app_ui.good.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.common.LocalManageUtil;
import com.mvp.helper.WCallBack;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderPackActivityView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.OrderPackActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.ChangeAddressEvent;
import com.wushi.lenovo.asia5b.app_event.NewAddressEvent;
import com.wushi.lenovo.asia5b.app_event.PostPackEvent;
import com.wushi.lenovo.asia5b.app_model.good.DeliveriesBean;
import com.wushi.lenovo.asia5b.app_model.good.OrderPackModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderPackServiceModel;
import com.wushi.lenovo.asia5b.app_model.good.bean.StepHelper;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModelIml;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.OrderGoodBean;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_model.profile.AddressModel;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.AddServicesAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderPaymentMethodAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.view.OrderAddressView;
import com.wushi.lenovo.asia5b.app_ui.other.OrderPackBeforeNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.other.OrderPackNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.ChangeAddressActivity;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.NewAddressActivity;
import com.wushi.lenovo.asia5b.app_ui.shopcar.adapter.OrderPackGoodsAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zhangyuncai on 2020/3/6.
 * 申请打包
 */
public class OrderPackActivity extends BaseMvpActivity<OrderPackActivityView, OrderPackActivityPresenter> implements OrderPackActivityView {
    @BindView(R.id.tv_ordercheck_address)
    TextView tv_ordercheck_address;
    @BindView(R.id.address_ordercheck)
    OrderAddressView address_ordercheck;
    @BindView(R.id.tv_ordercheck_intermethod)
    TextView tv_ordercheck_intermethod;
    @BindView(R.id.iv_ordercheck_info)
    ImageView iv_ordercheck_info;
    @BindView(R.id.rv_ordercheck_internationalmethod)
    RecyclerView internationalRecyclerView;
    @BindView(R.id.tv_ordercheck_addservice)
    TextView tv_ordercheck_addservice;
    @BindView(R.id.rv_ordercheck_addservice)
    RecyclerView addServiceRecyclerView;
    @BindView(R.id.rv_ordercheck_goods)
    RecyclerView rv_ordercheck_goods;
    @BindView(R.id.tv_ordercheck_totalactualweight)
    TextView tv_ordercheck_totalactualweight;
    @BindView(R.id.tv_ordercheck_totalvolweight)
    TextView tv_ordercheck_totalvolweight;
    @BindView(R.id.tv_ordercheck_totalm3)
    TextView tv_ordercheck_totalm3;
    @BindView(R.id.tv_ordercheck_interfee)
    TextView tv_ordercheck_interfee;
    @BindView(R.id.cb_ordercheck_insurance)
    CheckBox cb_ordercheck_insurance;
    @BindView(R.id.bt_ordercheck_submit)
    Button bt_ordercheck_submit;
    @BindView(R.id.tv_ordercheck_notice)
    TextView tv_ordercheck_notice;
    @BindView(R.id.ll_ordercheck_bottom)
    LinearLayout ll_ordercheck_bottom;
    @BindView(R.id.view_ordercheck_empty)
    View view_ordercheck_empty;
    //价格详细
    private OrderPackModel orderPackModel;
    private final MapHelper extraMap = MapHelper.newHashMap();
    //收货地址
    private AddressModel addressModel;
    private AddServicesAdapter addServiceAdapter;
    private OrderPackGoodsAdapter orderPackGoodsAdapter;
    private List<OrderGoodBean> inputGoods;

    public static void startOrderPackActivity(Context context, List<Integer> selectList, Serializable goods) {
        Intent intent = new Intent(context, OrderPackActivity.class);
        intent.putExtra("datas", (Serializable) selectList);
        intent.putExtra("goods", goods);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_orderpack;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        List<Integer> idList = (List<Integer>) getIntent().getSerializableExtra("datas");
        inputGoods = (List<OrderGoodBean>) getIntent().getSerializableExtra("goods");
        getPresenter().addGoods(idList);
        if (idList == null || idList.size() <= 0) {
            return;
        }

        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {


        EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_pi_notice), getString(R.string.shopcar_pi_notice_key),
                tv_ordercheck_notice, WebUrlType.shopcar_pi);

        //步骤1/2/3
        int i = 0;
        tv_ordercheck_address.setText(StepHelper.getStep(getString(R.string.shippingaddress), i++));
        tv_ordercheck_intermethod.setText(StepHelper.getStep(getString(R.string.internationalshippingmethod), i++));
        tv_ordercheck_addservice.setText(StepHelper.getStep(getString(R.string.addonservices), i++));

//        setGoodsView(inputGoods);
    }

    protected <GOOD extends GoodsModelIml> void setGoodsView(List<GOOD> goodsList) {
        /**
         * 显示商品列表
         */
        if (orderPackGoodsAdapter == null && goodsList != null) {
            orderPackGoodsAdapter = new OrderPackGoodsAdapter(goodsList);
            orderPackGoodsAdapter.inputGoods = inputGoods;
            rv_ordercheck_goods.setLayoutManager(new LinearLayoutManager(mActivity));
            rv_ordercheck_goods.setAdapter(orderPackGoodsAdapter);
        }
    }

    /**
     * 设置多选服务
     *
     * @param serviceModels
     */
    public void setAddServicesView(List<OrderPackServiceModel> serviceModels) {
        addServiceAdapter = new AddServicesAdapter(serviceModels == null ? new ArrayList() : serviceModels);
        addServiceRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        addServiceRecyclerView.setAdapter(addServiceAdapter);
    }

    /**
     * 设置国际运输方式
     *
     * @param deliveries
     */
    public void setInternationalDeliveryView(List<DeliveriesBean> deliveries) {
        OrderPaymentMethodAdapter internationalAdapter = new OrderPaymentMethodAdapter(deliveries == null ? new ArrayList() : deliveries);
        internationalRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        internationalRecyclerView.setAdapter(internationalAdapter);
        internationalAdapter.setOnItemClickListener((adapter, view, position) -> {
            DeliveriesBean bean = (DeliveriesBean) internationalAdapter.getItem(position);
            if (internationalAdapter.getSelectPosition() != position) {
                extraMap.put("international_delivery_method", bean.getCode());
                getPackData();//①
            }
            internationalAdapter.setSelectPosition(position);
        });
    }

    /**
     * 设置价格详细
     *
     * @param orderPackModel
     */
    private void setPriceDetailView(OrderPackModel orderPackModel) {
        this.orderPackModel = orderPackModel;
        if (orderPackModel != null) {
            tv_ordercheck_totalactualweight.setText(String.format("%s KG", orderPackModel.total_weight));
            tv_ordercheck_totalvolweight.setText(String.format("%s KG", orderPackModel.total_dimension_weight));
            tv_ordercheck_totalm3.setText(String.format("%s M³", orderPackModel.total_m3));
            //预估国际费用
            if (orderPackModel.estimated_international_charges != null) {
                tv_ordercheck_interfee.setText(orderPackModel.estimated_international_charges.getText());
            }
            setAddServicesView(orderPackModel.addon_services);

            setGoodsView(orderPackModel.products);

            iv_ordercheck_info.setVisibility((orderPackModel.got_sensitive == 1) ? View.VISIBLE : View.GONE);
        } else {
            tv_ordercheck_totalactualweight.setText("-");
            tv_ordercheck_totalvolweight.setText("-");
            tv_ordercheck_totalm3.setText("-");
            //预估国际费用
            tv_ordercheck_interfee.setText("-");
            setAddServicesView(null);
            iv_ordercheck_info.setVisibility(View.GONE);
        }
        bt_ordercheck_submit.setEnabled(orderPackModel != null);

    }

    @Override
    protected void initData() {
        getPackData();
    }

    private void getPackData() {
        getPresenter().getPackData(extraMap);
    }

    @Override
    protected void initEvent() {

    }


    @OnClick({
            R.id.view_ordercheck_empty,
            R.id.tv_order_edit,
            R.id.bt_ordercheck_submit,
            R.id.iv_ordercheck_vol_icon,
            R.id.iv_ordercheck_interfee_icon,
            R.id.iv_ordercheck_info
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_ordercheck_interfee_icon:
                if (orderPackModel != null && orderPackModel.estimated_international_charges != null) {
                    ToastUtil.showLongToast(orderPackModel.estimated_international_charges.getFormula());
                }
                break;
            case R.id.iv_ordercheck_vol_icon:
                if (TextUtils.equals(LocalManageUtil.getAppLanguage(), "cn")) {
                    ToastUtil.showLongToast(getString(R.string.parcel_note_cn));
                } else {
                    ToastUtil.showLongToast(getString(R.string.parcel_note_en));
                }
                break;
            /**
             * 防止点击穿透到下层
             */
            case R.id.view_ordercheck_empty:
                break;
            case R.id.iv_ordercheck_info: {
                ToastUtil.showToast(getString(R.string.orderpayment_mingantishi));
                break;
            }
            /**
             * 修改地址
             */
            case R.id.tv_order_edit: {
                startActivity(new Intent(this, ChangeAddressActivity.class));
            }
            break;
            /**
             * 新建地址
             */
            case R.id.bt_order_newaddres: {
                Intent intent = new Intent(this, NewAddressActivity.class);
                intent.putExtra("OrderPayment", true);
                startActivity(intent);
            }
            break;
            /**
             * 申请打包
             */
            case R.id.bt_ordercheck_submit: {
                if (addressModel == null) {
                    ToastUtil.showToast(getString(R.string.orderpayment_fillup_address_delivery));
                    return;
                }
                OrderPackBeforeNoticeDialog dialog = new OrderPackBeforeNoticeDialog(mActivity);
                dialog.title = getString(R.string.orderpack_before_notice_title);
                dialog.content = getString(R.string.orderpack_before_notice);
                dialog.ok = getString(R.string.orderpack_before_notice_accept);
                dialog.cancel = getString(R.string.cancel);
                dialog.setCallBack(new WCallBack<Boolean>() {
                    @Override
                    public void callback(Boolean aBoolean) {
                        if (aBoolean) {
                            getPresenter().postPack(addServiceAdapter.selectAddService);
                        }
                    }
                });
                dialog.show();
            }
            break;
            default:
                break;
        }

    }

    @Override
    public void getInternationalDeliveryMethodResult(List<DeliveriesBean> deliveries) {
        setInternationalDeliveryView(deliveries);
    }

    @Override
    public void getAddressModelResult(AddressModel addressModel) {
        this.addressModel = addressModel;
        address_ordercheck.setAddressView(addressModel);
    }

    @Override
    public void getPackDataResult(OrderPackModel orderPackModel) {
        view_ordercheck_empty.setVisibility(View.GONE);
        setPriceDetailView(orderPackModel);
    }

    @Override
    public void postPackResult() {
        OrderPackNoticeDialog dialog = new OrderPackNoticeDialog(mActivity);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
        dialog.show();
        EventBus.getDefault().post(new PostPackEvent());

    }

    /**
     * 地址改动通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onChangeAddress(ChangeAddressEvent event) {
        if (event != null && event.addressModel != null) {
            this.addressModel = event.addressModel;
            address_ordercheck.setAddressView(addressModel);
            extraMap.clear();
            getPresenter().addressModel = addressModel;
            getPackData();
        }


    }

    /**
     * 新建地址通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onNewAddressEvent(NewAddressEvent event) {
        if (event != null) {
            if (addressModel == null) {
                extraMap.clear();
                getPackData();
            }
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
